package com.song.estore.dao;

import com.song.estore.domain.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Created by 范姣姣 on 2015/10/22.
 */
public class UserDao {
    private SessionFactory sessionFactory;


    private Session getSession(){
        return sessionFactory.getCurrentSession();
    }


    public User findbyPassword(String email,String password){

        return (User) getSession().createQuery("from User where email=? and password=?")
                .setString(0,email)
                .setString(1,password)
                .uniqueResult();
    }
    public boolean findUserExists(String email) {
        return (getSession().createQuery("from User where email=?")
                .setString(0, email)
                .list().size()) > 0;
    }

    public int addUser(User user){
        if(!findUserExists(user.getEmail())){
            return getSession().createSQLQuery("insert into user(email, password, nickname, role, active, activecode) values(?,?,?,?,?,?)")
                    .setString(0,user.getEmail())
                    .setString(1,user.getPassword())
                    .setString(2,user.getNickname())
                    .setString(3,user.getRole())
                    .setInteger(4,user.getActive())
                    .setString(5,user.getActivecode())
                    .executeUpdate();
        }
        return 0;
    }


    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

}
